import { FC, useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
import { createStyles } from 'antd-style';
import { Flex } from 'antd';

const useStyle = createStyles(({ css }) => ({
  bar: css`
    position: absolute;
    left: 0;
    bottom: 0;
    height: 2px;
    background-color: var(--ycx-primary-color);
  `,
}));

type Props = {
  activeKey: string;
  onChange: (key: string) => void;
};
const Tabs: FC<Props> = ({ activeKey, onChange }) => {
  const { styles } = useStyle();
  const options = [
    {
      label: '轨迹点',
      key: 'location',
    },
    {
      label: '停车点',
      key: 'parkingLocation',
    },
    {
      label: '报警列表',
      key: 'alarmList',
    },
  ];
  const optionRefs = useRef<(HTMLDivElement | null)[]>([]);
  const [barStyle, setBarStyle] = useState({
    x: 24,
    width: 0,
  });

  useEffect(() => {
    const findIndex = options.findIndex((i) => i.key === activeKey);
    const selectOption = optionRefs.current[findIndex];
    if (selectOption) {
      setBarStyle({
        width: selectOption.clientWidth,
        x: selectOption.offsetLeft,
      });
    }
  }, [activeKey]);

  return (
    <>
      <Flex gap={24}>
        {options.map((item, index) => (
          <div
            key={item.key}
            className="cursor-pointer select-none text-center"
            style={{
              color:
                activeKey === item.key ? 'var(--ycx-font-color-l1)' : 'var(--ycx-font-color-l3)',
            }}
            onClick={() => onChange(item.key)}
            ref={(el) => (optionRefs.current[index] = el)}
          >
            {item.label}
          </div>
        ))}

        <motion.div
          className={styles.bar}
          animate={{ x: barStyle.x, width: barStyle.width }}
          transition={{
            type: 'spring',
            stiffness: 600,
            damping: 40,
          }}
        />
      </Flex>
    </>
  );
};

export default Tabs;
